﻿using MFTool;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using MF_Base.Model;
using UIBase;
using System.Configuration;
using System.Data;

namespace PortalLTE.Controllers
{

    public class LoginController : Controller
    {
        [NoCheckLoginAttr]
        public ActionResult Index()
        {
            HttpCookie cookie = Request.Cookies[CommonStr.LoginCookieKey];
            if (cookie != null && cookie[CommonStr.LoginCookieNameKey] != null)
            {
                string name = cookie[CommonStr.LoginCookieNameKey];
                FillSession(name);
                return RedirectToAction("Index", "Main");
            }

            return View();
        }

        [NoCheckLoginAttr]
        //[LoggerFilter(Description="用户登录操作")]
        public JsonResult UserLogin()
        {
            string name = "";
            if (Request.Form["Name"] != null)
            {
                name = Request.Form["Name"].ToString();
            }

            string pwd = "";
            if (Request.Form["Pwd"] != null)
            {
                pwd = Md5.GetMd5Str32(Request.Form["Pwd"]);
            }

            SqlHelper sqlhelper = new SqlHelper(EnumConn.MF_Base.ToString());
            DataTable userDt = new DataTable();
            
            userDt = sqlhelper.ExcuteTable("select top 1 * from MF_User where LoginName = '{0}'".ReplaceArg(name));

            Dictionary<string, object> userDic = new Dictionary<string, object>();
            //可登录
            if (userDt.Rows.Count > 0)
            {
                userDic = userDt.Rows[0].ToDic();
            }

            if (userDic != null && userDic.GetValue("PassWord") == pwd)
            {
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userDic["RealName"].ToString(), DateTime.Now, DateTime.Now.AddMinutes(30), true, userDic["Id"].ToString());
                var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));

                cookie.HttpOnly = true;
                cookie.Domain = FormsAuthentication.CookieDomain;
                cookie.Path = FormsAuthentication.FormsCookiePath;
                HttpContext.Response.Cookies.Add(cookie);

                FillSession(name, userDic);
                return Json(true);
            }
            return Json(false);
        }

        private void FillSession(string name, Dictionary<string, object> userDic = null)
        {
            if (Session[CommonStr.SessionUserKey] != null && Session[CommonStr.SessionRoleFuncKey] != null)
                return;

            SqlHelper sqlhelper = new SqlHelper(EnumConn.MF_Base.ToString());
            if (userDic == null && sqlhelper.Exist())
            {               
                var userDt = sqlhelper.ExcuteTable("select top 1 * from MF_User where LoginName = '{0}'".ReplaceArg(name));
                if (userDt.Rows.Count == 0) return;
                userDic = userDt.Rows[0].ToDic();                
            }
            Session[CommonStr.SessionUserKey] = userDic;

            if(sqlhelper.Exist())
            {
                var userRolesDt = sqlhelper.ExcuteTable("select * from MF_RoleUser where MF_UserId = '{0}'".ReplaceArg(userDic.GetValue("Id")));
                var userRoleIds = string.Join("','", userRolesDt.ToList().Select(a => a["MF_RoleId"].ToString()));
                var roleFuncsDt = sqlhelper.ExcuteTable(@"select distinct MF_Func.* from MF_FuncRole 
                                          inner join MF_Func on MF_Func.Id = MF_FuncRole.MF_FuncId where MF_FuncRole.MF_RoleId in ('{0}')".ReplaceArg(userRoleIds));
                var roleFuncs = roleFuncsDt.ToList<MF_Func>();
                Session[CommonStr.SessionRoleFuncKey] = roleFuncs;
            }            
        }
    }
}
